package cn.uniquesoft.controller;

import javax.servlet.http.HttpServletRequest;

import cn.uniquesoft.service.IDicDetailsService;
import cn.uniquesoft.service.ISearchService;
import cn.uniquesoft.util.HttpUtil;
import cn.uniquesoft.vo.DicDetailsVO;
import cn.uniquesoft.vo.SearchVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.uniquesoft.controller.base.BaseController;
import cn.uniquesoft.manager.ClientManager;
import cn.uniquesoft.service.IUserService;
import cn.uniquesoft.service.base.IBaseService;
import cn.uniquesoft.util.ContextHolderUtils;
import cn.uniquesoft.util.Md5Util;
import cn.uniquesoft.util.SaltUtil;
import cn.uniquesoft.vo.AnswerVO;
import cn.uniquesoft.vo.UserVO;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/user")
public class UserController extends BaseController<UserVO> {
    @Value("${user.default.pwd}")
    private String defaultPwd = "";
    @Value("${jstx.url}")
    private String jstxUrl;
    @Value("${jstx.orgname}")
    private String jstxOrgName;
    @Value("${jstx.appname}")
    private String jstxAppName;


    private IUserService userService;
    @Autowired
    private IDicDetailsService dicDetailsService;

    public UserController(IUserService userService) {
        super();
        this.userService = userService;
        this.baseService = (IBaseService<UserVO>) userService;
        this.indexName = "user/index";
    }


    @RequestMapping(value = "/userInfo")
    public String userInfo(Model model) {
        UserVO userVO = null;
        try {
            userVO = ClientManager.getInstance().getClient().getUser();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (userVO == null) {
            return "/login/index";
        }
        model.addAttribute("userVO", userVO);
        model.addAttribute("cname", userVO.getCname());
        return "user/userinfo";
    }


    @Override
    public AnswerVO save(UserVO item) {
        AnswerVO answerVO = new AnswerVO();
        UserVO oldUserVO = this.userService.getUserByName(item.getCname());
        if (oldUserVO == null) {
            String csalt = SaltUtil.random4Number();
            String cloginpwd = Md5Util.md5(defaultPwd);
            item.setCpassword(Md5Util.md5pwd(cloginpwd, csalt));
            item.setCsalt(csalt);
            String cusertype = "";
            DicDetailsVO dicDetailsVO = new DicDetailsVO();
            dicDetailsVO.setCkey("iusertype");
            dicDetailsVO.setCvalue(String.valueOf(item.getIusertype()));
            List<DicDetailsVO> dicDetailsVOList = this.dicDetailsService.findAll(dicDetailsVO);
            if (dicDetailsVOList.size() == 1) {
                cusertype = dicDetailsVOList.get(0).getCname();
            }
            item.setCusertype(cusertype);
            int i = this.userService.save(item);
            if (i > 0) {
                String param = "{\"username\":\"" + item.getCname() + "\",\"password\":\"" + item.getCname() + "\",\"nickname\":\"" + item.getCname() + "\"}";
                String msg = HttpUtil.doHttpsPostJson(jstxUrl + jstxOrgName + "/" + jstxAppName + "/users", param);
                if (null != msg && msg.length() > 0) {
                    answerVO.setSuccess(true);
                    answerVO.setMsg("新增成功!");
                } else {
                    answerVO.setSuccess(false);
                    answerVO.setMsg("新增失败,即时通信注册失败!");
                    this.userService.remove(item);
                }
            } else {
                answerVO.setSuccess(false);
                answerVO.setMsg("新增失败!");
            }
            return answerVO;
        } else {
            answerVO.setSuccess(false);
            answerVO.setMsg("该账号已存在！");
            return answerVO;
        }
    }

    @Override
    public AnswerVO edit(UserVO item) {
        String cusertype = "";
        DicDetailsVO dicDetailsVO = new DicDetailsVO();
        dicDetailsVO.setCkey("iusertype");
        dicDetailsVO.setCvalue(String.valueOf(item.getIusertype()));
        List<DicDetailsVO> dicDetailsVOList = this.dicDetailsService.findAll(dicDetailsVO);
        if (dicDetailsVOList.size() == 1) {
            cusertype = dicDetailsVOList.get(0).getCname();
        }
        item.setCusertype(cusertype);
        return super.edit(item);
    }

    //充值密码
    @RequestMapping(value = "/resetPwd")
    @ResponseBody
    public AnswerVO resetPwd(int iid, HttpServletRequest req) {
        AnswerVO answerVO = new AnswerVO();
        String csalt = SaltUtil.random4Number();
        String cloginpwd = Md5Util.md5(defaultPwd);
        cloginpwd = Md5Util.md5pwd(cloginpwd, csalt);
        UserVO userVO = new UserVO();
        userVO.setIid(iid);
        userVO.setCsalt(csalt);
        userVO.setCpassword(cloginpwd);
        int i = this.userService.resetPwd(userVO);
        if (i > 0) {
            answerVO.setSuccess(true);
            answerVO.setMsg("密码重置为6个1!");

        } else {
            answerVO.setSuccess(false);
            answerVO.setMsg("修改失败!");
        }
        return answerVO;

    }


    //修改密码
    @RequestMapping(value = "/updatePwd")
    @ResponseBody
    public AnswerVO updatePwd(String newPwd, HttpServletRequest req) {
        AnswerVO answer = new AnswerVO();
        UserVO userVO = null;
        try {
            userVO = ClientManager.getInstance().getClient().getUser();
        } catch (Exception e) {
            e.printStackTrace();
        }
        String pwdSalt = SaltUtil.random4Number();
        newPwd = Md5Util.md5(newPwd);
        userVO.setCpassword(Md5Util.md5pwd(newPwd, pwdSalt));
        userVO.setCsalt(pwdSalt);
        int i = this.userService.resetPwd(userVO);
        if (i > 0) {
            answer.setSuccess(true);
            answer.setMsg("密码修改成功!");
            ClientManager.getInstance().removeClient(ContextHolderUtils.getSession().getId());
        } else {
            answer.setSuccess(false);
            answer.setMsg("修改失败!");
        }
        return answer;
    }

    @Override
    public AnswerVO removeByIds(String ids) {
        AnswerVO answerVO = new AnswerVO();
        if (null == ids || ids.length() == 0) {
            answerVO.setMsg("请选择用户后再删除");
            answerVO.setSuccess(false);
            return answerVO;
        }
        List<UserVO> userVOList = this.userService.findIn(ids);
        for (UserVO userVO : userVOList) {
            String msg = HttpUtil.doDelete(jstxUrl + jstxOrgName + "/" + jstxAppName +"/users/" + userVO.getCname());
            if (null != msg && msg.length() > 0) {
                answerVO = super.removeById(userVO.getIid());
            } else {
                answerVO.setMsg("即时通信删除失败，删除用户失败!");
                answerVO.setSuccess(false);
                break;
            }
        }
        return answerVO;

    }
}
